﻿using System;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.XPath;
using System.Data.OleDb;
using IBM.Data.DB2;
using SAC.Helper;
using SAC.sqlHelper;

public partial class Admin_ManagePower : System.Web.UI.Page
{
    string xmlpath = "";
    string webpath = "ManagePower.aspx";
    //string webpath = "~/Admin/ManagePower.aspx";
    string errMsg = "";
    DAL.DALRole dr = new DAL.DALRole();
    BLL.BLLRole bl = new BLL.BLLRole();
    XmlDocument xmldoc = new XmlDocument();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Session.Contents["xmlpath"] != null)
                {
                    treeMenuPower.Nodes.Clear();
                    xmlpath = Session.Contents["xmlpath"].ToString();
                    Session.Contents["xmlpath"] = xmlpath;
                    //新建个DataSource指向要绑定的文件
                    XmlDataSource xds = new XmlDataSource();
                    xds.DataFile = xmlpath;
                    XmlDocument xmlDocument = xds.GetXmlDocument();
                    //把根节点的东东和treeView实例根节点群丢进去递归
                    BindXmlToTreeView(xmlDocument.DocumentElement, treeMenuPower.Nodes);
                    if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "")
                    {
                        string id = Request.QueryString["id"].ToString();
                        string rolename = dr.GetRoleNameById(id, out errMsg);
                        this.lblRoleName.Text = rolename;

                        ShowTreeCheck(rolename, treeMenuPower.Nodes);
                    }
                    treeMenuPower.ExpandAll();
                }
            }
            catch
            {

            }
        }
    }

    //确定分配
    protected void btnSure_Click(object sender, EventArgs e)
    {
        if (this.lblRoleName.Text != "尚未选择任何角色")
        {
            xmlpath = Session.Contents["xmlpath"].ToString();
            xmldoc.Load(xmlpath);
            //XmlNode xnode = xmldoc.DocumentElement.FirstChild;
            //XmlNode xnode = xmldoc.DocumentElement;
            //TreeNode tNode = new TreeNode();
            string rolename = this.lblRoleName.Text;
            if (rolename != "")
            {
                //SaveTreeCheck(rolename, xnode, treeMenuPower.Nodes);
                SaveTreeCheck1(rolename);
            }

            ShowTreeCheck(rolename, treeMenuPower.Nodes);
        }
    }

    //取消
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearTreeCheck(treeMenuPower.Nodes);
        this.lblRoleId.Text = "";
        this.lblRoleName.Text = "尚未选择任何角色";
    }

    //加载XML文件
    protected void LoadXml(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile.FileName.ToString() != "")
        {
            treeMenuPower.Nodes.Clear();
            // xmlpath = "D:\\CHDWEB\\WebMenu.xml";// FileUpload1.PostedFile.FileName.ToString();
            xmlpath = FileUpload1.PostedFile.FileName.ToString();
            Session.Contents["xmlpath"] = xmlpath;
            XmlDataSource xds = new XmlDataSource();
            xds.DataFile = xmlpath;
            XmlDocument xmlDocument = xds.GetXmlDocument();
            //把根节点的东东和treeView实例根节点群丢进去递归
            BindXmlToTreeView(xmlDocument.DocumentElement, treeMenuPower.Nodes);
            if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "")
            {
                string id = Request.QueryString["id"].ToString();
                string rolename = dr.GetRoleNameById(id, out errMsg);
                this.lblRoleName.Text = rolename;

                ShowTreeCheck(rolename, treeMenuPower.Nodes);
            }
            treeMenuPower.ExpandAll();
        }
    }

    //通过递归将XML节点生成treeview
    private void BindXmlToTreeView(XmlNode node, TreeNodeCollection tnc)
    {
        //获得节点字段值
        string strText = node.Attributes["caption"].Value;
        string owner = node.Attributes["owner"].Value;
        tnc.Add(new TreeNode(strText, owner));
        foreach (XmlNode n in node.ChildNodes)
        {
            //指向子节点和父节点的子节点群
            BindXmlToTreeView(n, tnc[tnc.Count - 1].ChildNodes);
        }

    }


    private void ShowTreeCheck(string rolename, TreeNodeCollection treeNodes)
    {
        foreach (TreeNode node in treeNodes)
        {
            string owner = node.Value.ToString();
            string[] val = owner.Split(',');
            for (int i = 0; i < val.Length; i++)
            {
                if (rolename == val[i])
                {
                    node.Checked = true;

                    break;
                }
            }
            ShowTreeCheck(rolename, node.ChildNodes);
        }
    }

    //显示treeview的check的状态
    //private void ShowTreeCheck1(string rolename, TreeNodeCollection tNode)
    //{
    //    int i = 0;
    //    int j = 0;
    //    int k = 0;
    //    int l = 0;


    //    //根目录
    //    if (IsChecked(rolename, xmldoc.ChildNodes[1]))
    //    {
    //        tNode[0].Checked = true;
    //    }
    //    else
    //    {
    //        tNode[0].Checked = false;
    //    }

    //    //第一层
    //    for (i = 0; i < tNode[0].ChildNodes.Count; i++)
    //    {
    //        if (IsChecked(rolename, xmldoc.ChildNodes[1].ChildNodes[i]))
    //        {
    //            tNode[0].ChildNodes[i].Checked = true;
    //        }
    //        else
    //        {
    //            tNode[0].ChildNodes[i].Checked = false;
    //        }
    //    }

    //    //第二层
    //    for(i = 0; i < tNode[0].ChildNodes.Count; i++)
    //    {
    //        for(j=0;j<tNode[0].ChildNodes[i].ChildNodes.Count;j++)
    //        {
    //            if (IsChecked(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j]))
    //            {
    //                tNode[0].ChildNodes[i].ChildNodes[j].Checked = true;
    //            }
    //            else
    //            {
    //                tNode[0].ChildNodes[i].ChildNodes[j].Checked = false;
    //            }
    //        }
    //    }

    //    //第三层
    //    for (i = 0; i < tNode[0].ChildNodes.Count; i++)
    //    {
    //        for (j = 0; j < tNode[0].ChildNodes[i].ChildNodes.Count; j++)
    //        {
    //            for (k = 0; k < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes.Count; k++)
    //            {
    //                if (IsChecked(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j].ChildNodes[k]))
    //                {
    //                    tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].Checked = true;
    //                }
    //                else
    //                {
    //                    tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].Checked = false;
    //                }
    //            }
    //        }
    //    }

    //    //第四层
    //    for (i = 0; i < tNode[0].ChildNodes.Count; i++)
    //    {
    //        for (j = 0; j < tNode[0].ChildNodes[i].ChildNodes.Count; j++)
    //        {
    //            for (k = 0; k < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes.Count; k++)
    //            {
    //                for (l = 0; l < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[l].ChildNodes.Count; l++)
    //                {
    //                    if (IsChecked(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes[l]))
    //                    {
    //                        tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes[l].Checked = true;
    //                    }
    //                    else
    //                    {
    //                        tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes[l].Checked = false;
    //                    }
    //                }
    //            }
    //        }
    //    }

    //}


    //判断这个节点在当前角色中check的状态是什么
    //private bool IsChecked(string rolename, XmlNode xnode)
    //{
    //    bool flag = false;
    //    string owner = xnode.Attributes["owner"].Value.ToString();
    //    string[] val = owner.Split(',');
    //    for (int i = 0; i < val.Length; i++)
    //    {
    //        if (rolename == val[i])
    //        {
    //            flag = true;
    //            break;
    //        }
    //        else
    //        {
    //            flag = false;
    //        }
    //    }
    //    return flag;
    //}

    private void ClearTreeCheck(TreeNodeCollection treeNodes)
    {
        foreach (TreeNode node in treeNodes)
        {
            if (node.Checked)
            {
                node.Checked = false;
            }
            ClearTreeCheck(node.ChildNodes);
        }
    }

    //这个方法有问题
    //private void SaveTreeCheck(string rolename, XmlNode xnode, TreeNodeCollection tNode)
    //{
    //    if (xnode.HasChildNodes)//判断当前XML节点下有无子节点
    //    {
    //        foreach (TreeNode TN in tNode)//遍历特定XML文件节点的所有子节点
    //        {
    //            bool flag = true;
    //            bool flag2 = false;
    //            string owner = xnode.Attributes["owner"].Value.ToString();
    //            string[] val = owner.Split(',');
    //            if (TN.Checked == true)
    //            {
    //                for (int i = 0; i < val.Length; i++)
    //                {
    //                    if (rolename == val[i])
    //                    {
    //                        flag = false;
    //                        break;
    //                    }
    //                }
    //                if (flag == true)
    //                {
    //                    string nowner = owner + rolename + ",";
    //                    xnode.Attributes["owner"].Value = nowner;
    //                }
    //            }
    //            else
    //            {
    //                for (int i = 0; i < val.Length; i++)
    //                {
    //                    if (rolename == val[i])
    //                    {
    //                        flag2 = true;
    //                        break;
    //                    }
    //                }
    //                if (flag2 == true)
    //                {
    //                    //string nowner = owner - (rolename + ",");
    //                    //node.Attributes["owner"].Value = nowner;
    //                }
    //            }

    //            SaveTreeCheck(rolename, xnode.FirstChild, TN.ChildNodes);//递归调用
    //        }

    //    }

    //}

    private void SaveTreeCheck1(string rolename)
    {
        int i = 0;
        int j = 0;
        int k = 0;
        int l = 0;

        xmldoc.Load(xmlpath);
        TreeNodeCollection tNode = treeMenuPower.Nodes;
        //根目录
        Save(rolename, xmldoc.ChildNodes[1], tNode[0]);

        //第一层
        for (i = 0; i < tNode[0].ChildNodes.Count; i++)
        {
            Save(rolename, xmldoc.ChildNodes[1].ChildNodes[i], tNode[0].ChildNodes[i]);
        }

        //第二层
        for (i = 0; i < tNode[0].ChildNodes.Count; i++)
        {
            for (j = 0; j < tNode[0].ChildNodes[i].ChildNodes.Count; j++)
            {
                Save(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j], tNode[0].ChildNodes[i].ChildNodes[j]);
            }
        }

        //第三层
        for (i = 0; i < tNode[0].ChildNodes.Count; i++)
        {
            for (j = 0; j < tNode[0].ChildNodes[i].ChildNodes.Count; j++)
            {
                for (k = 0; k < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes.Count; k++)
                {
                    Save(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j].ChildNodes[k], tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k]);
                }
            }
        }

        //第四层
        for (i = 0; i < tNode[0].ChildNodes.Count; i++)
        {
            for (j = 0; j < tNode[0].ChildNodes[i].ChildNodes.Count; j++)
            {
                for (k = 0; k < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes.Count; k++)
                {
                    for (l = 0; l < tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes.Count; l++)
                    {
                        Save(rolename, xmldoc.ChildNodes[1].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes[l], tNode[0].ChildNodes[i].ChildNodes[j].ChildNodes[k].ChildNodes[l]);
                    }
                }
            }
        }

    }

    //进行逻辑判断并修改xml中的owner属性
    private void Save(string rolename, XmlNode xnode, TreeNode TN)
    {
        bool flag = true;
        bool flag2 = false;
        string owner = xnode.Attributes["owner"].Value.ToString();
        string[] val = owner.Split(',');
        if (TN.Checked == true)
        {
            for (int i = 0; i < val.Length; i++)
            {
                if (rolename == val[i])
                {
                    flag = false;
                    break;
                }
            }
            if (flag == true)
            {
                string nowner = owner + rolename + ",";
                xnode.Attributes["owner"].Value = nowner;
                xmldoc.Save(xmlpath);
            }
        }
        else
        {
            for (int i = 0; i < val.Length; i++)
            {
                if (rolename == val[i])
                {
                    flag2 = true;
                    break;
                }
            }
            if (flag2 == true)
            {
                string del = rolename + ",";
                string nowner = Convert.ToString(owner.Replace(del, ""));
                xnode.Attributes["owner"].Value = nowner;
                xmldoc.Save(xmlpath);
            }
        }

    }


    protected void PermTreeView_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    {
        TreeNodeCollection node = e.Node.ChildNodes;
        foreach (TreeNode item in node)
        {
            item.Checked = e.Node.Checked;
            CheckNode(item.ChildNodes, e.Node.Checked);
        }
        e.Node.ExpandAll();

    }

    public void CheckNode(TreeNodeCollection node, bool selected)
    {
        foreach (TreeNode item in node)
        {
            item.Checked = selected;
            CheckNode(item.ChildNodes, selected);
        }
    }

    //点击加载按钮运行加载方法
    protected void BtnLoad_Click(object sender, EventArgs e)
    {
        LoadXml(sender, e);
    }

    //将XML上传至数据库
    protected void BtnUp_Click(object sender, EventArgs e)
    {
        if (Session.Contents["xmlpath"] != null)
        {
            bool ret = true;
            string message = "";
            string DBtype = dr.GetDBtype();
            xmlpath = Session.Contents["xmlpath"].ToString();
            string filename = xmlpath.Substring(xmlpath.LastIndexOf("\\") + 1);
            FileStream fs = new FileStream(xmlpath, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            if (DBtype == "SQL")//上传至SQLSERVER数据库
            {
                try
                {
                    SqlConnection sqlconn = SAC.sqlHelper.DBsql.GetConnection();

                    string sqlstr = "update XMLMENU set O_XML=@xmlfile where MENU='Webmenu'";
                    SqlCommand sqlcmd = new SqlCommand(sqlstr, sqlconn);
                    SqlParameter db2para = new SqlParameter("@xmlfile", SqlDbType.VarBinary, bytes.Length);
                    db2para.Value = bytes;
                    sqlcmd.Parameters.Add(db2para);
                    sqlcmd.ExecuteNonQuery();
                    SAC.sqlHelper.DBsql.CloseConnection(sqlconn);
                }
                catch (Exception ce)
                {
                    errMsg = ce.Message;
                    ret = false;
                }
            }

            else//上传至DB2数据库
            {
                try
                {
                    OleDbConnection con = new OleDbConnection(bl.RetDB2conn());
                    con.Open();
                    OleDbCommand oledbcom = new OleDbCommand("update XMLMENU set O_XML=?where MENU='Webmenu'", con);
                    oledbcom.Parameters.Add("?", bytes);
                    oledbcom.ExecuteNonQuery();
                    con.Close();

                }
                catch (Exception ce)
                {
                    errMsg = ce.Message;
                    ret = false;
                }

            }

            if (ret == true)
            {
                message = "上传成功！";
            }
            else
            {
                message = "上传失败！请检查数据库设置！";
            }
            Response.Write("<script>alert('" + message + "')</script>");

        }
    }
}
